define(['jquery', 'bootstrap', 'backend', 'addtabs', 'table', 'echarts', 'echarts-theme', 'template'], function ($, undefined, Backend, Datatable, Table, Echarts, undefined, Template) {
	
	/* 获取从后端tdsum.php传过来的数据 */
	
	var obj=eval(Config.demo);
	var dates=new Array;
	var normals=new Array;
	var faults=new Array;
	var OffEquips=new Array;
	var order='';
	var phivrange=new Array;
	var phivnumber=new Array;
	var creexy = new Array();
	var creeheadxy = new Array();
	var creeheadA = new Array();
	var creeheadG = new Array();
	var creeheadH = new Array();
	var creeheadI = new Array();
	var creeheadJ = new Array();
	
	//$("#equips").val("9999999999");
    var Controller = {
        index: function () {
			
			
			/* 测试------------- */
				
			/* ---------------------------------------- */
			
			
			/* --------------维修首件停机分钟数及停机 fixfaultsminutestc*/
			
			/* ----------------测试 fixfaults*/
			
			
			// 基于准备好的dom，初始化echarts实例---柏拉图
			var myChartRa1 = Echarts.init(document.getElementById('echartRa1'), 'dark');
			var myChartFlux = Echarts.init(document.getElementById('echartFlux'), 'dark');
			var myChartVF = Echarts.init(document.getElementById('echartVF'), 'dark');
			var myChartColor = Echarts.init(document.getElementById('echartColor'), 'dark');
            //var myChart1 = Echarts.init(document.getElementById('echart1'), 'walden');
			//柱状图数据
			var myChartRa = Echarts.init(document.getElementById('echartRa'), 'dark');
			var myChartR9 = Echarts.init(document.getElementById('echartR9'), 'dark');
			var myChartPhiv = Echarts.init(document.getElementById('echartPhiv'), 'dark');
			var myChartVFRange = Echarts.init(document.getElementById('echartVFRange'), 'dark');
			var myChartLdom = Echarts.init(document.getElementById('echartLdom'), 'dark');
			var myChartVflow = Echarts.init(document.getElementById('echartVflow'), 'dark');
			var myCharttest = Echarts.init(document.getElementById('echarttest'), 'dark');
			
			
			
			//--------------------------------
			var colors=["red","blue","green","black","orange","purple"]
			var phivarr = [];
			var phivvalue=[];
			var Percen=[];
            // 指定图表的配置项和数据-------柏拉图--------------------
			$("#query").click(function() {
				order=$("#order").val()
				console.log(order);
				$.ajax({
					type: 'POST',
					url: "http://172.31.3.27:84/index.php/bpidata/Bpiad/getcreecode",
					data: "order=" + order,
					dataType: "JSON",
					success: function(ret) {
						var objs=eval(ret['range']);
						console.log(ret);
						
						// getinformationcreecode(ret,'PhiV',myChartPhiv);
						getinformationcreecode(ret['range'],'Ra1',myChartRa1,'显指');
						getinformationcreecode(ret['range1'],'0',myChartFlux,'亮度');
						getinformationcreecode(ret['range1'],'1',myChartVF,'电压');
						getinformationcreecode(ret['range1'],'2',myChartColor,'色区');
						// getinformationcreecode(ret,'VF',myChartVF);
						getinformationcreerange(ret['range'],'Ra',myChartRa,'显指');
						getinformationcreerange(ret['range'],'R9',myChartR9,'R9');
						getinformationcreerange(ret['range1'],'0',myChartPhiv,'亮度');
						getinformationcreerange(ret['range1'],'1',myChartVFRange,'电压');
						getinformationcreerange(ret['range'],'Ldom',myChartLdom,'波长');
						getinformationcreerange(ret['range'],'Vflow',myChartVflow,'Vflow');
						getcreexy(ret['creexy'],ret['creeheadxy'],myCharttest);
			
					}
				});
			});
		function getinformationcreecode(ret,code,echar,name){
			phivarr = [];
			phivvalue=[];
			phivnumber=[];
			Percen=[];
			Percen[0]=0;
			var range=0;
			var lengths=0;
			for(var k in ret)
			{
				if(ret[k]['codename']==code){
					phivarr.push(ret[k]['coderange']);
					phivvalue.push(ret[k]['number']/1000);
				}
			}
			if(phivarr.length<5){
				for(var i=phivarr.length;i<5;i++){
					phivarr[i]='index';
					phivvalue[i]=0;
				}
			}
			var sum=0;//对codenumber进行求和
			var sumlen=0;//柏拉图需要对当前len数组求和
			for (var j=0;j<phivvalue.length;j++){
				sum=sum+parseInt(phivvalue[j]);
			}
			console.log(phivarr);
			console.log(phivvalue);
			for(var i=0;i<phivvalue.length;i++){
				sumlen=sumlen+parseInt(phivvalue[i]);
				Percen[i+1]=sumlen/sum*100;
			}
			
			getphivechars(echar,name);
			
		}
		
		function getinformationcreerange(ret,code,echar,name){
			phivarr = [];
			phivvalue=[];
			phivnumber=[];
			Percen=[];
			
			//console.log('"'+code+'"');
			var range=0;
			var lengths=0;
			if(code!='0' && code!='1'){
				for(var k in ret){
					if(ret[k]['codename']==code){
						
						phivrange=ret[k]['coderange'].split('~');
						//phivranges=ret['range'][k]['coderange'].split('~');
						phivarr.push(phivrange[0]);
						phivarr.push(phivrange[1]);
						range=phivrange[1]-phivrange[0];
						phivnumber[lengths]=ret[k]['coderange']+'~'+ret[k]['number']/1000;
						lengths=lengths+1;
					}
					
				}
			}
			else{
				for(var k in ret){
					if(ret[k]['codename']==code){
						console.log(ret[k]['codename'],code,ret[k]['rangecode']);
						phivrange=ret[k]['rangecode'].split('~');
						
						phivarr.push(phivrange[0]);
						phivarr.push(phivrange[1]);
						range=phivrange[1]-phivrange[0];
						phivnumber[lengths]=parseFloat(phivrange[0])+'~'+parseFloat(phivrange[1])+'~'+ret[k]['number']/1000;
						lengths=lengths+1;
					}
				}
			}
			var max = Math.max.apply(null, phivarr);
			var min = Math.min.apply(null, phivarr);
			phivarr=[];
			phivarr[0]=(min-range)+'~'+(min);
			var len=(max-min)/range;
			if(len<5){
				len=5;
				for(var i=phivnumber.length;i<len;i++){
					phivnumber[i]=(min+range*i)+'~'+(min+range*(i+1))+'~'+'0';
					
				}
				
			}
			for(var i=1;i<len;i++){
				phivarr[i]=phivarr[i-1].split('~')[1]+'~'+(parseFloat(phivarr[i-1].split('~')[1])+range);
			}
			console.log(phivarr);
			console.log(phivnumber);
			var sum=0;//对codenumber进行求和
			var sumlen=0;//柏拉图需要对当前len数组求和
			for (var j=0;j<phivnumber.length;j++){
				sum=sum+parseInt(phivnumber[j].split('~')[2]);
			}
			for (var j=0;j<phivnumber.length;j++){
				var f='';
				var vl;
				for(var i=0;i<phivarr.length;i++){
					
					if(phivarr[i]==phivnumber[j].split('~')[0]+'~'+phivnumber[j].split('~')[1]){
						phivvalue[i]=phivnumber[j].split('~')[2];
						f='true';
					}
				}
				if(f==''){
					phivvalue[i]=0;
				}
				
			}
			console.log(phivvalue);
			getcreerange(echar,name);
			
		}
		
		function getphivechars(echar,name){
			
            echar.setOption({
                title: {
                    text: name,//图的主题
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    }
                    
                },
                legend: {
                    selectedMode: false,
                    data: ['QTY(K)', '%']//[折线图线的格式，连接点的格式]
                },
                toolbox: {
                    show: true,
                    feature: {
                        mark: { show: true },
                        dataView: { show: true, readOnly: false },
                        restore: { show: true },
                        saveAsImage: { show: true }
                    }
                },
                calculable: true,
                xAxis: [{
                    type: 'category',
                    data: phivarr,//['top1', 'top2', 'top3', 'top4', 'top5', 'top6'],//（区间代码）
                    splitLine:true
                    //data:[]
                },{
                    type: 'category',
                    show:false,
                    boundaryGap : false,
                    data: ['Cosco', 'CMA', 'APL', 'OOCL', 'Wanhai', 'Zim',"333"],//（从小到大的区间值）
                    splitLine:false
                }],
				
				
				
                yAxis: [{
                        type: 'value',
                        boundaryGap: [0, 0.1],
                        splitLine:false
                    },
                    {
                        type: 'value',
                        name: '百分比',//右列的名称
                        axisLabel: {
                            formatter: '{value}'
                        },
                        splitLine:false
                    }
                ],
                series: [{
                        name: 'QTY(K)',
                        type: 'bar',
                        //barGap:'10%',
                        barCategoryGap: '0%',
                        itemStyle: {
                            normal: {
                                color: function(obj){
                                    if(obj.dataIndex>=0){
                                        return colors[obj.dataIndex];
                                    }
                                },
                                barBorderColor: 'tomato',
                                barBorderWidth: 1,
                                barBorderRadius: 2,
                                label: {
                                    show: true,
                                    position: 'insideTop'
                                }
                            }
                        },
                        data: phivvalue//[300, 200, 180, 150, 120, 50]//柱状图数据
                    },
                    {
                        name: '%',
                        type: 'line',
                        xAxisIndex: 1,
                        yAxisIndex: 1,
                        data:Percen// [0, 30,80, 100]//百分比折线图数据
                    }
 
                ]
            });
		}
		
		
		function getcreerange(echar,name){
			
            echar.setOption({
                title: {
                    text: name,//图的主题
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    }
                    
                },
                legend: {
                    selectedMode: false,
                    data: ['QTY(K)']//[折线图线的格式，连接点的格式]
                },
                toolbox: {
                    show: true,
                    feature: {
                        mark: { show: true },
                        dataView: { show: true, readOnly: false },
                        restore: { show: true },
                        saveAsImage: { show: true }
                    }
                },
                calculable: true,
                xAxis: [{
                    type: 'category',
                    data: phivarr,//['top1', 'top2', 'top3', 'top4', 'top5', 'top6'],//（区间代码）
                    splitLine:true
                    //data:[]
                },{
                    type: 'category',
                    show:false,
                    boundaryGap : false,
                    data: ['Cosco', 'CMA', 'APL', 'OOCL', 'Wanhai', 'Zim',"333"],//（从小到大的区间值）
                    splitLine:false
                }],
				
				
				
                yAxis: [{
                        type: 'value',
                        boundaryGap: [0, 0.1],
                        splitLine:false
                    },
                    
                ],
                series: [{
                        name: 'QTY(K)',
                        type: 'bar',
                        //barGap:'10%',
                        barCategoryGap: '0%',
                        itemStyle: {
                            normal: {
                                color: function(obj){
                                    if(obj.dataIndex>=0){
                                        return colors[obj.dataIndex];
                                    }
                                },
                                barBorderColor: 'tomato',
                                barBorderWidth: 1,
                                barBorderRadius: 2,
                                label: {
                                    show: true,
                                    position: 'insideTop'
                                }
                            }
                        },
                        data: phivvalue//[300, 200, 180, 150, 120, 50]//柱状图数据
                    }
 
                ]
            });
		}
		// var tArray = new Array(); //先声明一维
		// for(var k=0;k<i;k++){ //一维长度为i,i为变量，可以根据实际情况改变
		//		tArray[k]=new Array(); //声明二维，每一个一维数组里面的一个元素都是一个数组；
		// for(var j=0;j<p;j++){ //一维数组里面每个元素数组可以包含的数量p，p也是一个变量；
		// 		tArray[k][j]=""; //这里将变量初始化，我这边统一初始化为空，后面在用所需的值覆盖里面的值
		 // }
		// }
		function getcreexy(ret,head,echar){
			var A=0;
			var G=0;
			var H=0;
			var I=0;
			var J=0;
			var xy=0;
			creeheadA = [];
			creeheadG = [];
			creeheadH = [];
			creeheadI = [];
			creeheadJ = [];
			creeheadxy=[];
			creexy=[];
			for(var k in ret)
			{
				creexy[k]=new Array();
				creexy[k][0]=ret[k]['x'];
				creexy[k][1]=ret[k]['y'];
			}
			for(var k in head)
			{
				if(head[k]['step']==3 || head[k]['step']==5){
					creeheadxy[xy]=new Array();
					creeheadxy[xy][0]=head[k]['x'];
					creeheadxy[xy][1]=head[k]['y'];
					xy=xy+1;
				}
				if(head[k]['step']=='A'){
					creeheadA[A]=new Array();
					creeheadA[A][0]=head[k]['x'];
					creeheadA[A][1]=head[k]['y'];
					A=A+1;
				}
				if(head[k]['step']=='G'){
					creeheadG[G]=new Array();
					creeheadG[G][0]=head[k]['x'];
					creeheadG[G][1]=head[k]['y'];
					G=G+1;
				}
				if(head[k]['step']=='H'){
					creeheadH[H]=new Array();
					creeheadH[H][0]=head[k]['x'];
					creeheadH[H][1]=head[k]['y'];
					H=H+1;
				}
				if(head[k]['step']=='I'){
					creeheadI[I]=new Array();
					creeheadI[I][0]=head[k]['x'];
					creeheadI[I][1]=head[k]['y'];
					I=I+1;
				}
				if(head[k]['step']=='J'){
					creeheadJ[J]=new Array();
					creeheadJ[J][0]=head[k]['x'];
					creeheadJ[J][1]=head[k]['y'];
					J=J+1;
				}
				
				
			}
			console.log(creeheadA,creeheadG,creeheadH,creeheadI,creeheadJ);
			echar.setOption({
				title : {
					text: 'x,y散点分布图',
					
				},
				grid: {
					left: '3%',
					right: '7%',
					bottom: '3%',
					containLabel: true
				},
				tooltip : {
					// trigger: 'axis',
					showDelay : 0,
					formatter : function (params) {
						if (params.value.length > 1) {
							return params.seriesName + ' :<br/>'
							+ params.value[0] + ','
							+ params.value[1] + '';
						}
						else {
							return params.seriesName + ' :<br/>'
							+ params.name + ' : '
							+ params.value + ' ';
						}
					},
					axisPointer:{
						show: true,
						type : 'cross',
						lineStyle: {
							type : 'dashed',
							width : 1
						}
					}
				},
				toolbox: {
					feature: {
						dataZoom: {},
						brush: {
							type: ['rect', 'polygon', 'clear']
						}
					}
				},
				brush: {
				},
				legend: {
					data: ['分布图'],
					left: 'center'
				},
				xAxis : [
					{
						type : 'value',
						//interval: 0.005, // 自定义显示X轴坐标显示间隔
						scale:true,
						axisLabel : {
							formatter: '{value}'
						},
						splitLine: {
							show: false
						}
					}
				],
				yAxis : [
					{
						type : 'value',
						scale:true,
						axisLabel : {
							formatter: '{value}'
						},
						splitLine: {
							show: false
						}
					}
				],
				series : [
					{
						name:'分布',
						type:'scatter',
						symbolSize: '3',
						data: creexy,
						markArea: {
							silent: true,
							itemStyle: {
								normal: {
									color: 'transparent',
									borderWidth: 0.5,
									borderType: 'dashed'
								}
							},
							data: [[{
								name: 'x,y散点分布图',
								xAxis: 'min',
								yAxis: 'min'
							}, {
								xAxis: 'max',
								yAxis: 'max'
							}]]
						},
						markPoint : {
							data : [
								{type : 'max', name: '最大值'},
								{type : 'min', name: '最小值'}
							]
						},
						markLine : {
							lineStyle: {
								normal: {
									type: 'solid'
								}
							},
							data : [
								{type : 'average', name: '平均值'},
								{ xAxis: 170 }
							]
						}
					},
					{
						id: 'XY',
						type: 'line',
						smooth: true,
						symbolSize: '1',
						data: creeheadxy
					},
					{
						id: 'A',
						type: 'line',
						smooth: false,
						symbolSize: '1',
						color:'black',
						lineStyle: {
								normal: {
									color:'black',
									type: 'solid'
								}
							},
						data: creeheadA
					},
					{
						id: 'G',
						type: 'line',
						smooth: true,
						symbolSize: '1',
						lineStyle: {
								normal: {
									color:'black',
									type: 'solid'
								}
							},
						data: creeheadG
					},
					{
						id: 'H',
						type: 'line',
						smooth: true,
						symbolSize: '1',
						lineStyle: {
								normal: {
									color:'black',
									type: 'solid'
								}
							},
						data: creeheadH
					},
					{
						id: 'I',
						type: 'line',
						smooth: true,
						symbolSize: '1',
						lineStyle: {
								normal: {
									color:'black',
									type: 'solid'
								}
							},
						data: creeheadI
					},
					{
						id: 'J',
						type: 'line',
						smooth: true,
						symbolSize: '1',
						lineStyle: {
								normal: {
									color:'black',
									type: 'solid'
								}
							},
						data: creeheadJ
					},
				]
			});
			//console.log(creexy);
			// echar.setOption({
				// title: {
                    // text: name,//图的主题
                // },
				// xAxis: {},
				// yAxis: {},
				// series: [{
					// symbolSize: 2,
					// data:creexy,
					// type: 'scatter'
				// }]
			// });
		}
//######################################################################		
		// myCharttest.setOption({
					// xAxis: {},
					// yAxis: {},
					// series: [{
						// symbolSize: 4,
						// data: [
							// [10.0, 8.04],
							// [8.0, 6.95],
							// [13.0, 7.58],
							// [9.0, 8.81],
							// [11.0, 8.33],
							// [14.0, 9.96],
							// [6.0, 7.24],
							// [4.0, 4.26],
							// [12.0, 10.84],
							// [7.0, 4.82],
							// [5.0, 5.68]
						// ],
						// type: 'scatter'
					// }]
				// });
//######################################################################
		
		
            // 使用刚指定的配置项和数据显示图表。
           
            //myChart1.setOption(option);

             //动态添加数据，可以通过Ajax获取数据然后填充
			 //getechar();
			 //getinformation();
			 
			 // setInterval(function (){
				 // getechar();
            // }, 1000*60*30);
			 
            setInterval(function () {
			   getinformation();
            }, 1000*60*10);

			function getechar(){
				$.ajax({
				type: 'POST',
				url:"http://172.31.3.27:84/index.php?s=/fastadmin/Tdsum/echar",//127.0.0.1:85,172.31.3.27:84
				
					dataType: 'JSON',
					success: function (ret) {
						//console.log(ret['JL']);
						var objs=eval(ret['JL']);
						for(var k in ret['JL'])
							{
								dates[k]=ret['JL'][k]['createdate'];
								normals[k]=ret['JL'][k]['normals'];
								faults[k]=-(ret['JL'][k]['faults']);
								OffEquips[k]=-(ret['JL'][k]['OffEquips']);
							}
					
					//按自己需求可以取消这个限制
						myChart.setOption({
							yAxis : [
								{
									type : 'category',
									axisTick : {show: false},
									data : dates//['周一','周二','周三','周四','周五','周六','周日']
								}
							],
							series: [{
								name:'运作',
								type:'bar',
								label: {
									normal: {
										show: true,
										position: 'inside'
									}
								},
								 data:  normals//[200, 170, 240, 244, 200, 220, 222 ]//{$result.bdfaultequips}
							},
							{
								name:'停机',
								type:'bar',
								stack: '总量',
								label: {
									normal: {
										show: true,
										position: 'inside'//'left'
									}
								},
								data:faults// [-20, -32, -10, -34, -19, -23, -22]
							},
							{
								name:'待机',
								type:'bar',
								label: {
									normal: {
										show: true,
										position: 'inside'
									}
								},
								 data:  OffEquips//[200, 170, 240, 244, 200, 220, 222 ]//{$result.bdfaultequips}
							},
							]
						});
					}
				});
			}
			function getinformation(){
				 $.ajax({
				   type: 'POST',
					url:"http://172.31.3.27:84/index.php?s=/fastadmin/Tdsum/selectfatdsum",
					
					dataType: 'JSON',
					success: function (ret) {
						/* 总机台数 */
						$("#equips").html(ret[44]);
						/* 各站停机数 */
						$("#faults").html(ret[0]);//停机总数
						$("#fixfaults").html(ret[1]);
						$("#firstfaults").html(ret[2]);
						$("#gjfaultequips").html(ret[3]);
						$("#hxfaultequips").html(ret[6]);
						$("#djfaultequips").html(ret[9]);
						$("#qgfaultequips").html(ret[12]);
						$("#fgfaultequips").html(ret[15]);
						$("#bdfaultequips").html(ret[18]);
						/* 各工站停机分钟数 */
						$("#faultsminutes").html(ret[21]);//
						$("#fixfaultsminutes").html(ret[22]);
						$("#firstfaultsminutes").html(ret[23]);
						$("#gjfaultsminutes").html(ret[24]);
						$("#hxfaultsminutes").html(ret[25]);
						$("#djfaultsminutes").html(ret[26]);
						$("#qgfaultsminutes").html(ret[27]);
						$("#fgfaultsminutes").html(ret[28]);
						$("#bdfaultsminutes").html(ret[29]);
						/* 各工站运行数 */
						$("#normals").html(ret[30]);//运行（开机）总数
						$("#gjnormalequips").html(ret[31]);
						$("#hxnormalequips").html(ret[32]);
						$("#djnormalequips").html(ret[33]);
						$("#qgnormalequips").html(ret[34]);
						$("#fgnormalequips").html(ret[35]);
						$("#bdnormalequips").html(ret[36]);
						/* 各站待机数 OffEquips*/
						$("#OffEquips").html(ret[37]);
						//console.log($("#OffEquips").html());
						
						//总稼动率
						console.log(ret[30]+"--"+ret[44]+"--"+ret[0]);
						//			机台总数-总停机数-总待机数/机台总数
						var zjdl = (((ret[44]-ret[0]-ret[37])/ret[44])*100).toFixed(2);
									//总运行数-总停机数/总运行数
						var scjdl = ((ret[30]-ret[0])/ret[30]*100).toFixed(2);
						$("#zongjiadonglv").html(zjdl+"%");
						//生产稼动率
						$("#shengchanjiadonglv").html(scjdl+"%");
					}
				});
			 }
			
			
            $(window).resize(function () {
                //myChart.resize();
				myChartRa1.resize();
				myChartFlux.resize();
				myChartVF.resize();
				myChartColor.resize();
            });

            $(document).on("click", ".btn-checkversion", function(){
                top.window.$("[data-toggle=checkupdate]").trigger("click");
            });
			
        }
    };
    return Controller;
});